package cn.outsourcing.supermarket.common;

import cn.outsourcing.supermarket.common.enums.ResultEnums;
import cn.outsourcing.supermarket.common.utils.StrUtils;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 返回结果对象
 *
 * @author gzkemays
 * @since 2021/10/15 20:14
 */
@Data
@NoArgsConstructor
public class Result {
  int errno;
  String errmsg;
  Object data;

  public static ResultBuilder builder() {
    return new ResultBuilder();
  }

  private Result(ResultBuilder builder) {
    this.errno = builder.errno;
    this.errmsg = builder.errmsg;
    this.data = builder.data;
  }

  private Result(ResultEnums enums) {
    this.errno = enums.getCode();
    this.errmsg = enums.getMsg();
  }

  interface ResultMethod {
    /**
     * 构造于 {@link ResultEnums} 参数
     *
     * @param enums 枚举值
     * @return 结果对象
     */
    Result buildByResultEnums(ResultEnums enums);
  }

  public static final class ResultBuilder implements ResultMethod {
    int errno;
    String errmsg;
    Object data;

    private ResultBuilder() {}

    public ResultBuilder errno(int errno) {
      this.errno = errno;
      return this;
    }

    public ResultBuilder errmsg(String errmsg) {
      this.errmsg = errmsg;
      return this;
    }

    public ResultBuilder data(Object data) {
      this.data = data;
      return this;
    }

    public ResultBuilder defaultError() {
      this.errmsg = "";
      this.errno = 0;
      return this;
    }

    public Result build() {
      Result result = new Result();
      result.setErrno(errno);
      result.setErrmsg(errmsg);
      result.setData(data);
      return result;
    }

    @Override
    public Result buildByResultEnums(ResultEnums enums) {
      this.errno = enums.getCode();
      this.errmsg = enums.getMsg();
      return new Result(this);
    }
  }

  public Result defaultError() {
    this.errmsg = "";
    this.errno = 0;
    return this;
  }

  public Result errno(int errno) {
    this.errno = errno;
    return this;
  }

  public Result errmsg(String errmsg) {
    this.errmsg = errmsg;
    return this;
  }

  @Override
  public String toString() {
    return StrUtils.clearNull(this);
  }
}
